// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <melon/executors/io_thread_pool_executor.h>
#include <pollux/exec/cursor.h>

namespace kumo::pollux::tool::trace {

class TraceReplayTaskRunner {
 public:
  explicit TraceReplayTaskRunner(
      core::PlanNodePtr plan,
      std::shared_ptr<core::QueryCtx> queryCtx) {
    cursorParams_.planNode = std::move(plan);
    cursorParams_.queryCtx = std::move(queryCtx);
    POLLUX_CHECK_NOT_NULL(cursorParams_.planNode);
    POLLUX_CHECK_NOT_NULL(cursorParams_.queryCtx);
  }

  /// Run the replaying task. Return the copied results if 'copyResults' is
  /// true or return null.
  std::pair<std::shared_ptr<exec::Task>, RowVectorPtr> run(
      bool copyResults = false);

  /// Max number of drivers. Default is 1.
  TraceReplayTaskRunner& maxDrivers(int32_t maxDrivers);

  /// Spilling directory, if not empty, then the task's spilling directory would
  /// be built from it.
  TraceReplayTaskRunner& spillDirectory(const std::string& dir);

  /// Splits of this task.
  TraceReplayTaskRunner& splits(
      const core::PlanNodeId& planNodeId,
      std::vector<exec::Split> splits);

 private:
  void addSplits(exec::Task* task);

  std::shared_ptr<RowVector> copy(const std::vector<RowVectorPtr>& results);

  exec::CursorParameters cursorParams_;
  melon::F14FastMap<core::PlanNodeId, std::vector<exec::Split>> splits_;
  bool noMoreSplits_ = false;
};
} // namespace kumo::pollux::tool::trace
